package carrot

import (
	"fmt"
	"log"
	"net/http"
	"time"

	"./logic"
	"./mvc"
)

// Application 直接响应接口
type Application struct {
	di     *logic.DI
	port   uint16
	server *http.Server
	status chan int
}

func createApplication(port uint16, di *logic.DI) *Application {
	return &Application{
		di:   di,
		port: port,
	}
}

// CreateHTTPServer 创建HTTP服务
func CreateHTTPServer(port uint16, di *logic.DI) {
	application := createApplication(port, di)
	application.start()
}

func (app *Application) start() {
	mux := http.NewServeMux()
	mux.HandleFunc("/**", func(writer http.ResponseWriter, request *http.Request) {
		app.onReceiveHTTPRequest(writer, request)
	})

	app.server = &http.Server{
		Addr:         fmt.Sprintf(":%d", app.port),
		Handler:      mux,
		WriteTimeout: time.Second * 30,
	}
	go func() {
		for {
			select {
			case app.status <- 0:
				log.Printf("Server started on port %d\n", app.port)
			case app.status <- 1:
				if err := app.server.Close(); err != nil {
					log.Println("Server closed with error: ", err)
				}
				log.Println("Server stoped")
			case app.status <- 2:
				if err := app.server.Close(); err != nil {
					log.Println("Server closed with error: ", err)
				}
				log.Println("Server stoped")
				app.start()
			}
		}
	}()
	app.status <- 0
	app.server.ListenAndServe()
}

// Stop 停止服务器
func (app *Application) Stop() {
	app.status <- 1
}

// Restart 重启服务器
func (app *Application) restart() {
	app.status <- 2
}

// Reload 重新加载配置等信息
func (app *Application) Reload() {

}

func (app *Application) onReceiveHTTPRequest(writer http.ResponseWriter, request *http.Request) {
	route := mvc.ParseRouter("")

}
